﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace LabMS.Web.OpenProject
{
    public partial class openprojectedit : Base.BasePage
    {
        public string strID = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            strPageUserType.Add("teacher");
            if (Request.QueryString["id"] == null)
            {
                Common.JShelper.JSAlert(Page, "err", "参数错误!");
                return;
            }
            strID = Request.QueryString["id"].ToString();
            if (!Page.IsPostBack)
            {

                LabMS.Model.OpentProject mopproject = checkQueryString(strID);
                if (mopproject == null)
                {
                    Common.JShelper.JSAlert(Page, "err2", "开放实验项目不存在!");
                    return;
                }
                bindDDL(mopproject);
                bind(mopproject);

                lbPageName.Text = mopproject.OP_ProjectName + "修改";
                lbCID.Text = mopproject.ID.ToString();
                AttachItemDataBind();

            }
            this.Page.Title = lbPageName.Text;

        }

        LabMS.Model.OpentProject checkQueryString(string strID)
        {
            LabMS.BLL.OpentProject bopproject = new LabMS.BLL.OpentProject();
            string strWhere = "ID =" + strID;
            List<LabMS.Model.OpentProject> listmopproject = bopproject.GetModelList(strWhere);
            if (listmopproject.Count == 0)
            {
                return null;
            }
            return listmopproject[0];
        }

        public void bindDDL(LabMS.Model.OpentProject mopproject)
        {
            LabMS.BLL.Lab blab = new LabMS.BLL.Lab();
            List<LabMS.Model.Lab> mLab = new List<LabMS.Model.Lab>();
            mLab = blab.GetModelList(" Lab_ParentID is null ");
            ddlLabName.DataSource = mLab;
            ddlLabName.DataTextField = "Lab_Name";
            ddlLabName.DataValueField = "Lab_Code";
            ddlLabName.DataBind();
            ddlLabName.SelectedValue = mopproject.Project_Lab;

            ExtendBLL.Dictionary eDictionary = new ExtendBLL.Dictionary();
            List<Model.Dictionary> listCClass = new List<LabMS.Model.Dictionary>();


            listCClass = eDictionary.GetItemListByDClass("shiyanleibie");
            ddlProjectCategory.DataSource = listCClass;
            ddlProjectCategory.DataTextField = "Name";
            ddlProjectCategory.DataValueField = "Code";
            ddlProjectCategory.DataBind();
            ddlProjectCategory.SelectedValue = mopproject.Project_Category;

            listCClass = eDictionary.GetItemListByDClass("shiyanleixing");
            ddlProjectType.DataSource = listCClass;
            ddlProjectType.DataTextField = "Name";
            ddlProjectType.DataValueField = "Code";
            ddlProjectType.DataBind();
            ddlProjectType.SelectedValue = mopproject.Project_Type;

            listCClass = eDictionary.GetItemListByDClass("shiyanyaoqiu");
            ddlProjectRequire.DataSource = listCClass;
            ddlProjectRequire.DataTextField = "Name";
            ddlProjectRequire.DataValueField = "Code";
            ddlProjectRequire.DataBind();
            ddlProjectRequire.SelectedValue = mopproject.Project_Require;

            listCClass = eDictionary.GetItemListByDClass("shiyanzheleibie");
            ddlProjectPartnerType.DataSource = listCClass;
            ddlProjectPartnerType.DataTextField = "Name";
            ddlProjectPartnerType.DataValueField = "Code";
            ddlProjectPartnerType.DataBind();
            ddlProjectPartnerType.SelectedValue = mopproject.Project_PartnerType;

            listCClass = eDictionary.GetItemListByDClass("shiyanxiangmulaiyuan");
            ddlProjectComFrom.DataSource = listCClass;
            ddlProjectComFrom.DataTextField = "Name";
            ddlProjectComFrom.DataValueField = "Code";
            ddlProjectComFrom.DataBind();
            ddlProjectComFrom.SelectedValue = mopproject.OP_ProSource;

            LabMS.Model.SysSetting msys = new LabMS.Model.SysSetting();
            ExtendBLL.SysSetting extendsys = new ExtendBLL.SysSetting();
            msys = extendsys.GetCurrentSetting();
            List<string> listYear = Common.GradeHelper.GetCurrentGrade((int)msys.CurrentYear, (int)msys.CurrentSemester, false);
            ddlOPGrade.DataSource = listYear;
            ddlOPGrade.DataBind();
            ddlOPGrade.Items.Insert(0, new ListItem("", "0"));
            ddlOPGrade.SelectedValue = mopproject.OP_Grade;

            ddlOPFunds.SelectedValue = mopproject.OP_Funds;
        }

        void bind(LabMS.Model.OpentProject mopproject)
        {
            tbOPContent.Text = mopproject.OP_OpenType;
            tbOPInCharge.Text = mopproject.OP_InCharge;
            tbOPPhone.Text = mopproject.OP_Phone;
            tbOPPlanningCourseTime.Text = mopproject.OP_PlanningCourseTime;
            tbOPProfessioanl.Text = mopproject.OP_Professioanl;
            tbOPReason.Text = mopproject.OP_AppIntro;
            tbProjectCode.Text = mopproject.OP_ProjectCode;
            tbProjectEndWeek.Text = mopproject.Project_EndWeek.Value.ToString();
            tbProjectName.Text = mopproject.OP_ProjectName;
            tbProjectStartWeek.Text = mopproject.Project_StartWeek.Value.ToString();

            ExtendBLL.Dictionary eDictionary = new ExtendBLL.Dictionary();
            List<Model.Dictionary> listCClass = new List<LabMS.Model.Dictionary>();
            listCClass = eDictionary.GetModelList(" DClass='xueke' and Code ='" + mopproject.Project_Subject + "'");
            tbProjectSubjectCode.Value = mopproject.Project_Subject;
            if (listCClass.Count > 0)
            {
                tbProjectSubjectName.Value = listCClass[0].Name;
            }

            LabMS.BLL.Teacher bteacher = new LabMS.BLL.Teacher();
            List<Model.Teacher> listteacher = new List<LabMS.Model.Teacher>();
            listteacher = bteacher.GetModelList(" Teacher_Code ='" + mopproject.OP_Teacher + "'");
            tbTeacherCode.Value = mopproject.OP_Teacher;
            if (listteacher.Count > 0)
            {
                tbTeacherName.Value = listteacher[0].Teacher_Name;
            }


            tbTeacherCode.Value = mopproject.OP_Teacher;
            lbAppDate.Text = mopproject.OP_AppTime.Value.ToShortDateString();
            lbAppPerson.Text = mopproject.OP_Applicant;

            #region 绑定学生列表
            ExtendBLL.ProjectAppointment eprojectapp = new ExtendBLL.ProjectAppointment();
            List<LabMS.Model.Student> listStudent = new List<LabMS.Model.Student>();
            listStudent = eprojectapp.GetStudentByProject(mopproject.OP_ProjectCode);

            string strHTML = "<table  id='studenlist' border='1' class='infoTable' style='width: 400px; border-collapse: collapse;'>";
            strHTML += "<thead>";
            strHTML += "<tr class='header'>";
            strHTML += "<td class='none'>";
            strHTML += "ID";
            strHTML += "</td>";

            strHTML += "<td>";
            strHTML += "学号";
            strHTML += "</td>";

            strHTML += "<td>";
            strHTML += "姓名";
            strHTML += "</td>";
            strHTML += "<td>";
            strHTML += "";
            strHTML += "</td>";
            strHTML += "</tr>";
            strHTML += "</thead>";
            strHTML += "<tbody>";
            tb_StudentIDs.Value = "";
            foreach (LabMS.Model.Student s in listStudent)
            {
                if (tb_StudentIDs.Value == "")
                {
                    tb_StudentIDs.Value += s.ID.ToString();
                }
                else
                {
                    tb_StudentIDs.Value += "," + s.ID.ToString();
                }
                strHTML += "<tr>";
                strHTML += "<td class='none'>";
                strHTML += s.ID.ToString();
                strHTML += "</td>";
                strHTML += "<td>";
                strHTML += s.Student_Code;
                strHTML += "</td>";
                strHTML += "<td>";
                strHTML += s.Student_Name;
                strHTML += "</td>";
                strHTML += "<td>";
                strHTML += "<a>删除</a>";
                strHTML += "</td>";
                strHTML += "</tr>";
            }
            strHTML += "</tbody>"; 
            strHTML += "</table>";
            tblistStudents.Value = strHTML;
            tblistEmpty.Value = "0";
            #endregion
        }

        protected void bnSave_Click(object sender, EventArgs e)
        {
            LabMS.BLL.OpentProject bopproject = new LabMS.BLL.OpentProject();
            string strWhere = "ID =" + lbCID.Text;
            List<LabMS.Model.OpentProject> listmopproject = bopproject.GetModelList(strWhere);
            if (listmopproject.Count == 0)
            {
                Common.JShelper.JSAlert(Page, "err2", "开放实验项目不存在!");
            }
            LabMS.Model.OpentProject moproject = listmopproject[0];

            #region 验证

            if (string.IsNullOrEmpty(tbProjectStartWeek.Text.Trim()) || string.IsNullOrEmpty(tbProjectEndWeek.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验周次不能为空!");
                return;
            }

            int iStartWeek = 0;
            int iEndWeek = 0;

            if (!(int.TryParse(tbProjectStartWeek.Text.Trim(), out iStartWeek) && int.TryParse(tbProjectEndWeek.Text.Trim(), out iEndWeek)))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验周次只能输入数字!");
                return;
            }
            if (iStartWeek > iEndWeek)
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验周次开始时间大于结束时间!");
                return;
            }
            if (iStartWeek > 20 || iEndWeek > 20)
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验周次过大!");
                return;
            }

            if (string.IsNullOrEmpty(tbTeacherCode.Value.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "指导老师不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(tb_StudentIDs.Value.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验学生不能为空!");
                return;
            }
            #endregion

            moproject.OP_ProjectName = tbProjectName.Text.Trim();
            moproject.OP_ProjectCode = tbProjectCode.Text.Trim();
            moproject.Project_Category = ddlProjectCategory.SelectedValue;
            moproject.Project_EndWeek = iEndWeek;
            moproject.Project_Lab = ddlLabName.SelectedValue;
            moproject.Project_PartnerType = ddlProjectPartnerType.SelectedValue;
            moproject.Project_Require = ddlProjectRequire.SelectedValue;
            moproject.Project_StartWeek = iStartWeek;
            moproject.Project_Subject = tbProjectSubjectCode.Value;
            moproject.Project_Type = ddlProjectType.SelectedValue;

            moproject.OP_AppIntro = tbOPReason.Text.Trim();
            moproject.OP_ProSource = ddlProjectComFrom.SelectedValue;
            moproject.OP_Professioanl = tbOPProfessioanl.Text.Trim();
            moproject.OP_PlanningCourseTime = tbOPPlanningCourseTime.Text.Trim();
            moproject.OP_Phone = tbOPPhone.Text.Trim();
            moproject.OP_InCharge = tbOPInCharge.Text.Trim();
            moproject.OP_Grade = ddlOPGrade.SelectedValue;
            moproject.OP_AppIntro = tbOPContent.Text.Trim();
            moproject.OP_Teacher = tbTeacherCode.Value.Trim();
            moproject.OP_OpenType = tbOPContent.Text.Trim();//实验内容

            LabMS.Model.SysSetting msys = new LabMS.Model.SysSetting();
            ExtendBLL.SysSetting extendsys = new ExtendBLL.SysSetting();
            msys = extendsys.GetCurrentSetting();
            moproject.SYear = msys.CurrentYear;
            moproject.Semester = msys.CurrentSemester;

            string strAlertContent = "保存成功!";
            moproject.OP_Audit = "0";
            if (((Button)sender).ID == "btnApp")
            {
                strAlertContent = "申请成功!";
                moproject.OP_Audit = "1";
            }
            moproject.OP_AppTime = DateTime.Now;
            moproject.OP_Applicant = lbAppPerson.Text;
            int iOpenProjectID = 0;
            try
            {
                bopproject.Update(moproject);
            }
            catch (Exception ex)
            {
                lbErr.Visible = true;
                lbErr.Text = ex.Message;
                return;
            }
            String[] listsID = tb_StudentIDs.Value.Split(',');
            LabMS.Model.ProjectAppointment projectapp = new LabMS.Model.ProjectAppointment();
            ExtendBLL.ProjectAppointment bprojectapp = new ExtendBLL.ProjectAppointment();
            bprojectapp.Del(" where OP_ProjectCode ='" + moproject.OP_ProjectCode + "'");
            for (int i = 0; i < listsID.Length; ++i)
            {
               
                projectapp.Appoint_ClassID = "0";
                projectapp.Appoint_ProID = 0;
                projectapp.OP_Appoint_ID = listsID[i].ToString();
                projectapp.OP_ProjectCode = moproject.OP_ProjectCode;
                projectapp.OP_Score = "";
                try
                {
                    bprojectapp.Add(projectapp);
                }
                catch (Exception ex)
                {
                    lbErr.Visible = true;
                    lbErr.Text = ex.Message;
                    bprojectapp.Del(" where OP_ProjectCode ='" + moproject.OP_ProjectCode + "'");
                    return;
                }
            }

            AttachmentItemSave(moproject);

            Common.JShelper.JSAlertAndRedirect(Page, "success", strAlertContent, "currentopenprojectlist.aspx");

        }

        protected bool AttachmentItemSave(LabMS.Model.OpentProject openprojectmodel) 
        {

            if (openprojectmodel != null) 
            {
                int Attach_ID = 0;
                if (openprojectmodel.Attachment != null)
                {
                    Attach_ID = openprojectmodel.Attachment.Value;
                    string[] array = itemIDs.Value.Split(',');
                    if (array[0] != "")
                    {
                        for (int n = 0; n < array.Length; n++)
                        {
                            if (array[n] != "0")
                            {
                                LabMS.BLL.AttachmentItem Attach = new LabMS.BLL.AttachmentItem();
                                int itemID = 0;
                                if (int.TryParse(array[n], out itemID))
                                {
                                    try
                                    {
                                        Attach.Delete(itemID);
                                    }
                                    catch
                                    {

                                    }
                                }
                            }
                        }
                    }
                }
                else
                {

                    ///有上传文件
                    if (HttpContext.Current.Request.Files.Count - 1 > 0)
                    {
                        LabMS.BLL.Attachment Attach = new LabMS.BLL.Attachment();
                        LabMS.Model.Attachment attamentmodel = new LabMS.Model.Attachment();
                        LabMS.BLL.OpentProject OpenProject = new LabMS.BLL.OpentProject();
                        try
                        {
                            Attach_ID = Attach.Add(attamentmodel);
                            openprojectmodel.Attachment = Attach_ID;
                            OpenProject.Update(openprojectmodel);
                            
                        }
                        catch
                        {
                            lb_Error.Text = "保存上传文件错误";
                        }
                    }

                }
                if (Attach_ID != 0)
                {
                    return SaveItem(Attach_ID);
                }
                else 
                {
                    return false;
                }
               

            }
            return false;

        }



        private bool SaveItem(int Attach_ID) 
        {
            bool saved = false;
            if (Attach_ID != 0) 
            {
                if (HttpContext.Current.Request.Files.Count - 1 > 0) 
                {
                    try
                    {
                        int count = HttpContext.Current.Request.Files.Count;
                        HttpFileCollection Files = HttpContext.Current.Request.Files;
                        string savePath = HttpContext.Current.Request.MapPath(@"../Content/UpLoadFile/");
                        List<string> fileName = LabMS.Common.FileUpload.SaveFiles(Files, savePath);

                        if (Attach_ID != 0)
                        {
                            LabMS.BLL.AttachmentItem AttachItem = new LabMS.BLL.AttachmentItem();
                            LabMS.Model.AttachmentItem attachmentitemmodel;
                            for (int n = 0; n < fileName.Count; n++)
                            {
                                if (fileName[n].Trim() != "")
                                {
                                    attachmentitemmodel = new LabMS.Model.AttachmentItem();
                                    attachmentitemmodel.Attach_ID = Attach_ID;
                                    attachmentitemmodel.Item_Address = "Content/UpLoadFile/" + fileName[n].Trim();
                                    attachmentitemmodel.Item_Name = fileName[n].Substring(0, fileName[0].LastIndexOf("_"));
                                    attachmentitemmodel.Item_Type = "3";
                                    AttachItem.Add(attachmentitemmodel);
                                }
                            }
                        }
                        saved = true;
                    }
                    catch (Exception ex)
                    {
                        lbErr.Text = ex.Message;
                    }
                    finally
                    {
                        
                    }
                }
            }
            return saved;
        }

        protected void AttachItemDataBind() 
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                int ID = 0;
                if (int.TryParse(Request.QueryString["ID"], out ID))
                {
                    LabMS.BLL.OpentProject OpenProject = new LabMS.BLL.OpentProject();
                    LabMS.Model.OpentProject openprojectmodel = new LabMS.Model.OpentProject();


                    LabMS.BLL.AttachmentItem AttachItem = new LabMS.BLL.AttachmentItem();
                    List<LabMS.Model.AttachmentItem> ls = new List<LabMS.Model.AttachmentItem>();

                    openprojectmodel = OpenProject.GetModel(ID);
                    if (openprojectmodel != null) 
                    {
                        if (openprojectmodel.Attachment != null) 
                        {
                            int Attach_ID = openprojectmodel.Attachment.Value;
                            if (Attach_ID != 0) 
                            {
                                ls = AttachItem.GetModelList("Attach_ID=" + Attach_ID);
                                if (ls.Count != 0)
                                {
                                    string strHTML = "<table>";
                                    for (int i = 0; i < ls.Count; i++)
                                    {
                                        strHTML += "<tr>";
                                        strHTML += "<td style='display:none;'>";
                                        strHTML += ls[i].ID;
                                        strHTML += "</td>";
                                        strHTML += "<td>";
                                        strHTML += "<a>";
                                        strHTML += "删除";
                                        strHTML += "</a>";
                                        strHTML += "</td>";
                                        strHTML += "<td>";
                                        strHTML += ls[i].Item_Name;
                                        strHTML += "</td>";
                                        strHTML += "</tr>";
                                    }
                                    strHTML += "</table>";
                                    itemlist.Value = strHTML;

                                }
                            }
                        }
                    }
                }
            }

            
        }
    }
}
